<template>
  <div class="main">
    <div class="login border-radius box-shadow">
      <div class="login-title">
        <div>{{ title }}</div>
        <div class="f-gray-color">欢迎回来，我们想念你！</div>
      </div>
      <div class="login-form">
        <!--登录注册表单-->
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" status-icon>
          <el-form-item prop="username">
            <el-input v-model="ruleForm.username" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="ruleForm.password" type="password" placeholder="请输入密码"></el-input>
          </el-form-item>
          <el-form-item v-if="title === '免费注册'" prop="confirmPassword">
            <el-input v-model="ruleForm.confirmPassword" type="password" placeholder="请再次输入密码" @keyup.enter.native="formSubmit"></el-input>
          </el-form-item>
          <el-form-item prop="code">
            <el-input v-model="ruleForm.code" placeholder="请输入验证码" @keyup.enter.native="formSubmit">
              <div slot="append">
                <el-image class="pointer" style="width: 120px;height: 40px;" :src="codeImgUrl" @click="getCodeImg"></el-image>
              </div>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button class="loginBtn" type="primary" round @click="formSubmit" :loading="loginLoading" @keyup.enter.native="formSubmit">{{ title }}</el-button>
          </el-form-item>
          <el-form-item>
            <nuxt-link to="/">
              <el-button class="loginBtn" type="success" round>回到首页</el-button>
            </nuxt-link>
            <div class="register" v-if="title === '登录' && config.disableRegister == true"><a href="javascript:;" class="f-gray-color" @click="register">没有账户？注册</a></div>
            <div class="register" v-if="title === '免费注册'"><a href="javascript:;" class="f-gray-color" @click="register">已有账户？登录</a></div>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import {mapMutations, mapState} from "vuex";

export default {
  //SEO优化
  head(){
    return{
      title: this.title + this.config.separate + this.config.name,
      meta: [
        { name: 'keywords', content: '登录,注册,' + this.config.keywords },
        { hid: 'description', name: 'description', content: this.config.description },
      ]
    }
  },
  data(){
    return{
      //标题
      title: "登录",
      //验证码
      codeImgUrl: "",
      //表单数据
      ruleForm: {
        username: null,
        password: null,
        confirmPassword: null,
        uuid: null,
        code: null,
        isFront: true
      },
      //表单校验
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
      },
      //登录按钮加载开关
      loginLoading: false
    }
  },
  async asyncData({ app, params }) {
    const { data } = await app.$api_config.getList();
    app.store.dispatch("set_config", data);
    return { config: data }
  },
  created(){
    //判断URL是否为注册
    if(this.$route.query.type === "register"){
      this.title = "免费注册";
    }
    if(this.$route.query.msg !== undefined){
      this.$message({
        message: this.$route.query.msg,
        type: "warning",
        duration: process.env.MSG_TIME
      })
    }
  },
  mounted() {
    this.getCodeImg();
  },
  methods: {
    ...mapMutations({
      SET_TOKEN: 'user/SET_TOKEN'
    }),
    //切换注册
    register(){
      if(this.title === "免费注册"){
        this.title = "登录";
      }else{
        this.title = "免费注册";
      }
    },
    //获取验证码
    getCodeImg(){
      this.$api_login.getCodeImg().then(res => {
        if(res.code === 200){
          this.ruleForm.uuid = res.uuid;
          this.codeImgUrl = "data:image/gif;base64," + res.img;
        }
      });
    },
    //表单提交
    formSubmit(){
      this.loginLoading = true;
      switch (this.title) {
        case "登录":
          this.$refs['ruleForm'].validate((valid) => {
            if(valid){
              this.$api_login.login(this.ruleForm).then(res => {
                if(res.code === 200){
                  this.SET_TOKEN(res.token);
                  let _this = this;
                  this.$message({
                    message: '登录成功，正在跳转',
                    type: 'success',
                    duration: process.env.MSG_TIME,
                    onClose: function (){
                      if(_this.$route.query.redirect !== undefined){
                        _this.$router.push(_this.$route.query.redirect);
                      }else{
                        _this.$router.push("/");
                      }
                    }
                  });
                }else{
                  this.loginLoading = false;
                  this.$message.error(res.msg);
                }
              })
            }else{
              this.$message.error("请填写登录信息");
              this.loginLoading = false;
              return false;
            }
          });
          break;
        case "免费注册":
          this.$refs['ruleForm'].validate((valid) => {
            if(valid){
              if(this.ruleForm.password !== this.ruleForm.confirmPassword){
                this.$message.error("两次输入的密码不一致");
                this.loginLoading = false;
                return false;
              }
              this.$api_login.register(this.ruleForm).then(res => {
                if(res.code === 200){
                  let _this = this;
                  this.$message({
                    message: '注册成功',
                    type: 'success',
                    duration: process.env.MSG_TIME,
                    onClose: function (){
                      _this.title = "登录";
                      _this.loginLoading = false;
                    }
                  });
                }else{
                  this.loginLoading = false;
                  this.$message.error(res.msg);
                }
              })
            }else{
              this.$message.error("请填写注册信息");
              this.loginLoading = false;
              return false;
            }
          });
          break;
      }
      this.getCodeImg();
    }
  }
}
</script>

<style scoped>
.main{
  position: fixed;
  width: 100%;
  height: 100%;
  background: url("@/static/image/login_bg.png") no-repeat fixed bottom center;
  background-size: 100% 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.login{
  padding: 15px;
  width: 375px;
  border-bottom: 1px solid #F0F0F0;
  background-color: #FFFFFF;
}
.login-title{
  padding: 30px 0;
  text-align: center;
}
.login-title div:nth-child(1){
  font-size: 22px;
  line-height: 30px;
}
.login-title div:nth-child(2){
  font-size: 14px;
  line-height: 30px;
}
.loginBtn{
  width: 100%;
}
.register{
  text-align: center;
  font-size: 14px;
}
</style>
<style>
.login .login-form .el-input-group__append{
  width: 120px;
  height: 40px;
  background-color: #FFFFFF;
  border: none;
  padding: 0;
}
</style>
